package types

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
)

//Command line length
const ()

type Data map[string]interface{}
type Request Data
type Response Data

func (data *Data) Request(method string, urlStr string) (resp *http.Response, err error) { //Send data by http
	//errs := ErrorControler{}
	buf, err := json.Marshal(data)
	//errs.CheckError(err)
	fmt.Println(err)
	buffer := bytes.NewBuffer(buf)
	test(buffer)
	req, err := http.NewRequest(method, urlStr, buffer)
	//errs.CheckError(err)
	fmt.Println(err)
	test(req)
	req.Header.Add("Content-Type", "application/json;charset=utf-8")
	resp, err = http.DefaultClient.Do(req)
	//errs.CheckError(err)
	fmt.Println(err)
	test(resp)
	return resp, err
}

func (data *Data) Put(url string) (resp *http.Response, err error) {
	resp, err = data.Request("PUT", url)
	return resp, err
}

func (data *Data) Delete(url string) (resp *http.Response, err error) {
	resp, err = data.Request("DELETE", url)
	return resp, err
}

func (data *Data) Post(url string) (resp *http.Response, err error) {
	buf, err := json.Marshal(data)
	fmt.Println(err)
	rd := bytes.NewBuffer(buf)
	resp, err = http.Post(url, "application/json;charset=utf-8", rd)
	return resp, err
}

func (data *Data) Get(url string) (resp *http.Response, err error) {
	resp, err = http.Get(url)
	return resp, err
}

func (data *Data) In(r io.Reader) {
	buf, err := ioutil.ReadAll(r)
	fmt.Println(err)
	json.Unmarshal(buf, data)
}

func (data Data) GetRequest() (req string, err error) {
	if v1, ok1 := data["REQUEST"]; !ok1 {
		err = errors.New("Can't find request!")
	} else {
		if v2, ok2 := v1.(string); !ok2 {
			err = errors.New("map[\"REQUEST\"]: error type!")
		} else {
			req = v2
		}
	}

	return req, err
}

func (data Data) Error() (err error) {
	if v, ok := data["ERROR"]; !ok {
		err = nil
	} else {
		bArr, _ := json.Marshal(v)
		err = errors.New(string(bArr))
	}
	return err
}

func (data Data) GetUserName() (name string, err error) {
	if v, ok := data["USERNAME"]; !ok {
		err = errors.New("Can't find username!")
	} else {
		if v2, ok2 := v.(string); !ok2 {
			err = errors.New("Username Error type!")
		} else {
			name = v2
		}

	}

	return name, err
}

func (data Data) GetPassWord() (pwd string, err error) {
	if v, ok := data["PASSWORD"]; !ok {
		err = errors.New("Can't find password!")
	} else {
		if v2, ok2 := v.(string); !ok2 {
			err = errors.New("Password Error type!")
		} else {
			pwd = v2
		}
	}

	return pwd, err
}

/*
func (data Data) GetValueByKey(key string) (value interface{}) {
	value, ok := data[key]
	if !ok {
		log.Fatal("Can't find:" + key)
	}
	return value
}
*/
